package com.jungle.app.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.jungle.app.domain.bo.ImgLinkDataBo;
import com.jungle.app.domain.entity.ImgLinkData;
import com.jungle.app.domain.vo.ImgLinkDataVo;
import com.jungle.app.repository.ImgLinkDataRepository;
import com.jungle.app.repository.SysOssRepository;
import com.jungle.app.service.IImgLinkDataService;
import com.jungle.base.my.config.MinioConfig;
import com.jungle.common.constant.MessageConstant;
import com.jungle.common.core.domain.PageQuery;
import com.jungle.common.core.page.TableDataInfo;
import com.jungle.common.exception.file.FileNameExistException;
import com.jungle.common.utils.StringUtils;
import com.jungle.base.my.utils.MinioUploadUtil;
import com.jungle.system.domain.SysOss;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.Predicate;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 图片链接数据Service业务层处理
 *
 * @author jungle
 * @date 2023-09-28
 */
@RequiredArgsConstructor
@Service
@Slf4j
public class ImgLinkDataServiceImpl implements IImgLinkDataService {

    private final ImgLinkDataRepository repository;

    private final SysOssRepository sysOssRepository;

    /**
     * 查询图片链接数据
     */
    @Override
    public ImgLinkDataVo queryById(String id) {
        return repository.findById(id).map(v -> com.jungle.common.utils.BeanCopyUtils.copy(v, ImgLinkDataVo.class)).orElse(null);
    }

    /**
     * 查询图片链接数据列表
     */
    @Override
    public TableDataInfo<ImgLinkDataVo> queryPageList(ImgLinkDataBo bo, PageQuery pageQuery) {
        Page<ImgLinkData> result = repository.findAll(getSpecification(bo), pageQuery.pageable());
        return TableDataInfo.build(result, ImgLinkDataVo.class);
    }

    /**
     * 查询图片链接数据列表
     */
    @Override
    public List<ImgLinkDataVo> queryList(ImgLinkDataBo bo) {
        return repository.findAll(getSpecification(bo)).stream()
                .map(v -> com.jungle.common.utils.BeanCopyUtils.copy(v, ImgLinkDataVo.class))
                .collect(Collectors.toList());
    }

    private Specification<ImgLinkData> getSpecification(ImgLinkDataBo bo) {
        return (root, query, cb) -> {
            Map<String, Object> params = bo.getParams();
            List<Predicate> predicates = new ArrayList<>();
            if (StringUtils.isNotBlank(bo.getHrefUrl())) {
                predicates.add(cb.equal(root.get("hrefUrl"), bo.getHrefUrl()));
            }
            if (StringUtils.isNotBlank(bo.getImgUrl())) {
                predicates.add(cb.equal(root.get("imgUrl"), bo.getImgUrl()));
            }
            if (StringUtils.isNotBlank(bo.getType())) {
                predicates.add(cb.equal(root.get("type"), bo.getType()));
            }
            if (StringUtils.isNotBlank(bo.getUseTo())) {
                predicates.add(cb.equal(root.get("useTo"), bo.getUseTo()));
            }
            if (StringUtils.isNotBlank(bo.getImgName())) {
                predicates.add(cb.equal(root.get("imgName"), bo.getImgName()));
            }
            return query.where(predicates.toArray(new Predicate[predicates.size()])).getRestriction();
        };
    }

    private final SysOssRepository ossRepository;
    private final MinioConfig prop;
    private final MinioUploadUtil minioUploadUtil;

    /**
     * 新增图片链接数据
     */
    @Override
    public Boolean insertByBo(ImgLinkDataBo bo) {
        ImgLinkData add = com.jungle.common.utils.BeanCopyUtils.copy(bo, ImgLinkData.class);
//        MultipartFile file = bo.getFile();
//        String url = minioUploadUtil.upload(file);
        SysOss sysOss = ossRepository.findById(bo.getOssId()).orElse(null);

        add.setImgUrl(sysOss.getUrl());
        add.setImgName(sysOss.getOriginalName());
        ImgLinkData imgData = repository.findByImgName(add.getImgName());
        if (ObjectUtil.isNotNull(imgData)) {
            log.info("文件名已存在，{}", imgData);
            throw new FileNameExistException(MessageConstant.FILE_NAME_EXIST);
        }
        validEntityBeforeSave(add);
        repository.saveAndFlush(add);
        bo.setId(add.getId());
        return true;
    }

    /**
     * 修改图片链接数据
     */
    @Override
    public Boolean updateByBo(ImgLinkDataBo bo) {
        ImgLinkData update = com.jungle.common.utils.BeanCopyUtils.copy(bo, ImgLinkData.class);
        validEntityBeforeSave(update);
        return repository.save(update) != null;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(ImgLinkData entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除图片链接数据
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<String> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        //删除文件
        List<Long> ossIds = repository.findAllById(ids).stream()
                .map(ImgLinkData::getOssId).collect(Collectors.toList());
        sysOssRepository.deleteAllById(ossIds);

        repository.deleteAllById(ids);
        return true;
    }

    @Override
    public List<ImgLinkDataVo>  exportExcel(ImgLinkDataBo bo, HttpServletResponse response) {
        return queryList(bo);
    }
}
